package com.longcai.piaojia.fragment;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.activity.GoodsInfoActivity;
import com.longcai.piaojia.activity.SearchActivity;
import com.longcai.piaojia.adapter.SearchHotGridAdapter;
import com.longcai.piaojia.adapter.SearchResultListAdapter;
import com.longcai.piaojia.conn.SearchHotGet;
import com.longcai.piaojia.conn.SearchResultGet;
import com.longcai.piaojia.widget.NoScrollGridView;
import com.longcai.piaojia.widget.NoScrollListView;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshListView;
import com.module.pull.PullToRefreshScrollView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilKeyBoard;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/8/3.
 */
public class NewSearchHotFragment extends BaseFragment {

//    @BoundView(R.id.search_hot_psv) private PullToRefreshScrollView pullToRefreshScrollView;
    @BoundView(R.id.search_hot_ptlv) private PullToRefreshListView pullToRefreshListView;
    private ListView search_hot_ptlv;

    @BoundView(R.id.search_gv) private GridView search_gv;
//    @BoundView(R.id.search_result_lv) private NoScrollListView search_result_lv;
//    private ScrollView scrollView;
    private SearchHotGridAdapter searchHotGridAdapter;
    private List<String> lists = new ArrayList<>();
    private SearchResultListAdapter searchResultListAdapter;
    public List<SearchResultGet.SearchResultEntity> lists_search = new ArrayList<>();
    public String searchStr = "";

    private SearchHotGet searchHotGet = new SearchHotGet(new AsyCallBack<SearchHotGet.SearchHotListEntity>(){

        @Override
        public void onSuccess(String toast, int type, SearchHotGet.SearchHotListEntity searchHotListEntity) throws Exception {
            super.onSuccess(toast, type, searchHotListEntity);

            lists.addAll(searchHotListEntity.data);
            searchHotGridAdapter.notifyDataSetChanged();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(getActivity(), toast, Toast.LENGTH_LONG).show();

        }

    });

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private SearchResultGet.SearchResultListEntity searchResultList;

    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullToRefreshListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    public SearchResultGet searchResultGet = new SearchResultGet(new AsyCallBack<SearchResultGet.SearchResultListEntity>(){

        @Override
        public void onEnd(String toast, int type) throws Exception {
            super.onEnd(toast, type);

            pullToRefreshListView.onPullDownRefreshComplete();
            pullToRefreshListView.onPullUpRefreshComplete();
            setLastUpdateTime();

        }

        @Override
        public void onSuccess(String toast, int type, SearchResultGet.SearchResultListEntity searchResultListEntity) throws Exception {
            super.onSuccess(toast, type, searchResultListEntity);

            searchResultList = searchResultListEntity;

            lists_search.addAll(searchResultListEntity.data);
            searchResultListAdapter.notifyDataSetChanged();

            search_hot_ptlv.setVisibility(View.VISIBLE);

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(getActivity(), toast, Toast.LENGTH_LONG).show();

        }

    });

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view_main = BoundViewHelper.boundView(this, inflater.inflate(R.layout.new_fragment_search_hot_main, null));

        View view = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) inflater.inflate(R.layout.fragment_search_hot, null)));

        search_gv.setHorizontalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(35));
        search_gv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(30));

        searchHotGridAdapter = new SearchHotGridAdapter(getActivity(), lists);
        search_gv.setAdapter(searchHotGridAdapter);

        pullToRefreshListView.setPullRefreshEnabled(true);
        pullToRefreshListView.setScrollLoadEnabled(false);
        pullToRefreshListView.setPullLoadEnabled(true);

        search_hot_ptlv = pullToRefreshListView.getRefreshableView();

        search_hot_ptlv.setVerticalScrollBarEnabled(false);
        search_hot_ptlv.setTag("[0,0,0,1]");
        search_hot_ptlv.setDividerHeight(1);
        search_hot_ptlv.setDivider(new ColorDrawable(ContextCompat.getColor(getActivity(), R.color.light_line_color)));
        search_hot_ptlv.setBackgroundResource(R.drawable.layer_solid_white_bottom_grey);
        search_hot_ptlv.setVisibility(View.GONE);

        search_hot_ptlv.addHeaderView(view);

        searchResultListAdapter = new SearchResultListAdapter(getActivity(), lists_search);
        search_hot_ptlv.setAdapter(searchResultListAdapter);

        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                lists.clear();
                lists_search.clear();

                searchHotGet.execute(getActivity());

                searchResultGet.title = searchStr;
                searchResultGet.page = 1;
                searchResultGet.execute(getActivity(), false);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                if (searchResultList != null && searchResultList.total != searchResultList.current_page) {

                    searchResultGet.page = searchResultList.current_page + 1;

                    searchResultGet.execute(getActivity(), false);

                } else {

                    pullToRefreshListView.onPullUpRefreshComplete();

                    pullToRefreshListView.onPullDownRefreshComplete();

                }

            }

        });

        search_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ((SearchActivity) getActivity()).closeKeybord();

                String str = lists.get(position);

                String searchNotes = BaseApplication.BasePreferences.readSearch();

                if (searchNotes.length() == 0) {

                    if (!searchNotes.contains(str)) {

                        String newStringNotes = str + "," + searchNotes;

                        BaseApplication.BasePreferences.saveSearch(newStringNotes);

                    }

                } else {

                    boolean isHad = true;

                    String[] searchArray = searchNotes.split(",");

                    for (int i = 0; i < searchArray.length; i++) {

                        if (searchArray[i].contains(str)) {

                            isHad = false;

                        }

                    }

                    if (isHad) {

                        String newStringNotes = str + "," + searchNotes;

                        BaseApplication.BasePreferences.saveSearch(newStringNotes);

                    }else{

                        String StringNotes = "";

                        for(int i = 0; i < searchArray.length; i++){

                            if (!searchArray[i].equals(str)) {

                                StringNotes = StringNotes + "," + searchArray[i];

                            }

                        }

                        String newStringNotes = str + StringNotes + ",";

                        BaseApplication.BasePreferences.saveSearch(newStringNotes);

                    }

                }

                if (SearchLastFragment.is_live) {

                    try {
                        ((SearchLastFragment.RefreshSearchNotes) getAppCallBack(SearchLastFragment.class)).refresh();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                searchStr = str;

                ((SearchActivity) getActivity()).search(searchStr);

//                lists_search.clear();
//
//                searchResultGet.title = searchStr;
//                searchResultGet.page = 1;
//                searchResultGet.execute(getActivity());

            }
        });

        search_hot_ptlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("id", lists_search.get(position-1).id));

//                closeKeyBord();

                UtilKeyBoard.closeKeybord(((SearchActivity) getActivity()).search_title_et, getActivity());

            }
        });

        searchHotGet.execute(getActivity());

        return view_main;
    }
}
